﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.Net.Mail;

namespace EuroAudit
{
    public partial class Users : System.Web.UI.Page
    {
        GlobalF GFunc = new GlobalF();

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["UserName"] == null | Session["UserName"].ToString() == "" | Session["UserName"].ToString() == "guest")
            {
                Response.Redirect("Login.aspx", true);
            }
            if (Session["IsAdmin"].ToString() == "1")
            {
                cmdNewG.Visible = true;
                cmdNewU.Visible = true;
            }
            else
            {
                return;
            }

            if (IsPostBack)
            {
                if (_RESULT.Text == "OKcmdDelUsr")
                {
                    cmdDelU_Click(sender, e);
                    _RESULT.Text = "";
                }
                if (_RESULT.Text == "OKcmdDelGroup")
                {
                    cmdDelG_Click(sender, e);
                    _RESULT.Text = "";
                }
            }
            //aizpildam lietotāju sarakstu
            LoadUsers();
            //aizpildam grupu sarakstu
            LoadGroups();
            //ielādējam uzstādījumus
            GFunc.InitO();
            /*
            if (pEditUser.Visible == true)
            {
                LoadGroupsToTable(txtGroupList.Text);
            }
            if (pEditGroups.Visible == true)
            {
                LoadUsersToTable(txtUserList.Text);
            }
            */

        }

        void LoadUsers()
        {
            DataSet dsList;
            //DataSet dsGroupList;
            TableHeaderCell thcNewCell;
            TableHeaderRow thrNewRow;
            TableCell tcNewCell;
            TableRow trNewRow;
            Button cmdEdit;
            string LastStruct = "";
            string CurrStruct = "";
            string LastNod = "";
            string CurrNod = "";
            //Button cmdGEdit;
            //string UsersInGroup;

            tUsers.Rows.Clear();
            //
            string QStr = "SELECT User, LongName, Descr, Email, Groups FROM users WHERE RecStatus=0 ORDER BY User";
            dsList = GFunc.GetData(QStr, "WebCNS", false);
            if (dsList.Tables.Count > 0)
            {
                if (dsList.Tables[0].Rows.Count > 0)
                {
                    thrNewRow = new TableHeaderRow();
                    thcNewCell = new TableHeaderCell();
                    thcNewCell.Text = "Labot";
                    thrNewRow.Cells.Add(thcNewCell);
                    foreach (DataColumn Col in dsList.Tables[0].Columns)
                    {
                        thcNewCell = new TableHeaderCell();
                        thcNewCell.Text = Col.ColumnName;
                        thrNewRow.Cells.Add(thcNewCell);
                    }
                    tUsers.Rows.AddAt(0, thrNewRow);

                    //CurrStruct = row["Strukturvieniba"].ToString();
                    //CurrNod = row["Nodala"].ToString();

                    foreach (DataRow row in dsList.Tables[0].Rows)
                    {
                        /*
                        //grupēšana pa struktūrvienībām un nodaļām netiek veikta
                        LastStruct = row["Strukturvieniba"].ToString();
                        LastNod = row["Nodala"].ToString();
                        if (LastStruct.Equals(CurrStruct) == false)
                        {
                            trNewRow = new TableRow();
                            tcNewCell = new TableCell();
                            tcNewCell.ColumnSpan = 3;
                            tcNewCell.Text = row["Strukturvieniba"].ToString() + "";
                            tcNewCell.Font.Bold = true;
                            trNewRow.Cells.Add(tcNewCell);
                            tUsers.Rows.Add(trNewRow);
                        }
                        if (LastNod.Equals(CurrNod) == false | LastStruct.Equals(CurrStruct) == false)
                        {
                            trNewRow = new TableRow();
                            tcNewCell = new TableCell();
                            tcNewCell.ColumnSpan = 3;
                            tcNewCell.Text = row["Nodala"].ToString() + "";
                            tcNewCell.Font.Bold = true;
                            trNewRow.Cells.Add(tcNewCell);
                            tUsers.Rows.Add(trNewRow);
                            CurrStruct = LastStruct;
                            CurrNod = LastNod;
                        }
                        */
                        trNewRow = new TableRow();
                        tcNewCell = new TableCell();
                        if (Session["IsAdmin"].ToString() == "1")
                        {
                            cmdEdit = new Button();
                            cmdEdit.ID = "UserEdit" + row["User"].ToString();
                            cmdEdit.Text = "Labot";
                            cmdEdit.CssClass = "cmdEdit";
                            cmdEdit.CommandArgument = row["User"].ToString();
                            cmdEdit.PostBackUrl = "#pEditUser";
                            cmdEdit.Click += new EventHandler(cmdEdit_Click);
                            tcNewCell.Controls.Add(cmdEdit);
                            Label BkmListU = new Label();
                            BkmListU.Text = "<a name=\"" + row["User"].ToString() + "\"></a>";
                            //BkmListU.Visible = false;
                            tcNewCell.Controls.Add(BkmListU);
                        }
                        trNewRow.Cells.Add(tcNewCell);
                        foreach (DataColumn Col in dsList.Tables[0].Columns)
                        {
                            tcNewCell = new TableCell();
                            tcNewCell.Text = row[Col].ToString() + "";
                            trNewRow.Cells.Add(tcNewCell);
                        }
                        tUsers.Rows.Add(trNewRow);

                    }
                }
            }
        }

        void cmdEdit_Click(object sender, EventArgs e)
        {
            string User2Edit;
            //int DelIndex;
            //atjaunojam grupu sarakstu
            //dsGroups.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvGroups.DataSource = GFunc.GetData("SELECT GroupName, Description FROM groups WHERE RecStatus=0 ORDER BY GroupName", "WebCNS", false);
            gvGroups.DataBind();

            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            User2Edit = b.ID.Substring(8);
            foreach (TableRow row in tUsers.Rows)
            {
                if (row.Cells.Count > 1)
                {
                    if (row.Cells[1].Text == User2Edit)
                    {
                        
                        txtNewUser.Text = "0";
                        txtUser.Enabled = false;
                        txtUser.Text = row.Cells[1].Text;
                        txtLongName.Text = row.Cells[2].Text;
                        txtPassword.Text = "";
                        txtPassword1.Text = "";
                        txtDescr.Text = row.Cells[3].Text;
                        txtEmail.Text = row.Cells[4].Text;
                        txtOldEmail.Text = row.Cells[4].Text;
                        txtGroups.Text = row.Cells[5].Text;
                       
                    }
                }
            }
            cmdCloseU.PostBackUrl = "#" + b.CommandArgument;
            pEditUser.Visible = true;
            pEditGroup.Visible = false;
            txtLongName.Focus();

        }

        void LoadGroups()
        {
            DataSet dsList;
            DataSet dsGroupList;
            TableHeaderCell thcNewCell;
            TableHeaderRow thrNewRow;
            TableCell tcNewCell;
            TableRow trNewRow;
            //Button cmdEdit;
            Button cmdGEdit;
            string UsersInGroup;

            tGroups.Rows.Clear();

            string QStr = "SELECT GroupID, GroupName, Description FROM groups WHERE RecStatus = 0 ORDER BY GroupName";
            dsGroupList = GFunc.GetData(QStr, "WebCNS", false);
            if (dsGroupList.Tables.Count > 0)
            {
                if (dsGroupList.Tables[0].Rows.Count > 0)
                {
                    thrNewRow = new TableHeaderRow();
                    thcNewCell = new TableHeaderCell();
                    thcNewCell.Text = "Labot";
                    thrNewRow.Cells.Add(thcNewCell);
                    /*foreach (DataColumn Col in dsGroupList.Tables[0].Columns)
                    {
                        thcNewCell = new TableHeaderCell();
                        thcNewCell.Text = Col.ColumnName;
                        thrNewRow.Cells.Add(thcNewCell);
                    }*/
                    thcNewCell = new TableHeaderCell();
                    thcNewCell.Text = "GroupID";
                    thrNewRow.Cells.Add(thcNewCell);
                    thcNewCell = new TableHeaderCell();
                    thcNewCell.Text = "GroupName";
                    thrNewRow.Cells.Add(thcNewCell);
                    thcNewCell = new TableHeaderCell();
                    //thcNewCell.Width = Unit.Pixel(50);
                    thcNewCell.Text = "Users";
                    thrNewRow.Cells.Add(thcNewCell);
                    thcNewCell = new TableHeaderCell();
                    thcNewCell.Text = "Description";
                    thrNewRow.Cells.Add(thcNewCell);

                    tGroups.Rows.AddAt(0, thrNewRow);

                    foreach (DataRow row in dsGroupList.Tables[0].Rows)
                    {
                        //pieprasam grupai piesaistīto lietotāju sarakstu
                        QStr = "SELECT User FROM users WHERE Groups LIKE '%;" + row["GroupName"].ToString() + ";%' ORDER BY User";
                        dsList = GFunc.GetData(QStr, "WebCNS", false);
                        UsersInGroup = ";";
                        if (dsList.Tables.Count > 0)
                        {
                            if (dsList.Tables[0].Rows.Count > 0)
                            {
                                foreach (DataRow UIGrow in dsList.Tables[0].Rows)
                                {
                                    UsersInGroup = UsersInGroup + UIGrow["User"].ToString() + ";";
                                }
                                //UsersInGroup = UsersInGroup.Substring(0, UsersInGroup.Length - 1);
                            }
                        }
                        trNewRow = new TableRow();
                        tcNewCell = new TableCell();
                        if (Session["IsAdmin"].ToString() == "1")
                        {
                            cmdGEdit = new Button();
                            cmdGEdit.ID = "GroupEdit" + row["GroupID"].ToString();
                            cmdGEdit.Text = "Labot";
                            cmdGEdit.CssClass = "cmdEdit";
                            cmdGEdit.CommandArgument = row["GroupID"].ToString();
                            cmdGEdit.PostBackUrl = "#pEditGroup";
                            cmdGEdit.Click += new EventHandler(cmdGEdit_Click);
                            tcNewCell.Controls.Add(cmdGEdit);
                            Label BkmListG = new Label();
                            BkmListG.Text = "<a name=\"" + row["GroupID"].ToString() + "\"></a>";
                            //BkmListG.Visible = false;
                            tcNewCell.Controls.Add(BkmListG);
                        }
                        trNewRow.Cells.Add(tcNewCell);

                        tcNewCell = new TableCell();
                        tcNewCell.Text = row["GroupID"].ToString();
                        trNewRow.Cells.Add(tcNewCell);
                        tcNewCell = new TableCell();
                        tcNewCell.Text = row["GroupName"].ToString();
                        trNewRow.Cells.Add(tcNewCell);
                        tcNewCell = new TableCell();
                        //tcNewCell.Width = Unit.Pixel(150);
                        tcNewCell.Text = UsersInGroup;
                        trNewRow.Cells.Add(tcNewCell);
                        tcNewCell = new TableCell();
                        tcNewCell.Text = row["Description"].ToString();
                        trNewRow.Cells.Add(tcNewCell);
                        /*foreach (DataColumn Col in dsList.Tables[0].Columns)
                        {
                            tcNewCell = new TableCell();
                            tcNewCell.Text = row[Col].ToString();
                            trNewRow.Cells.Add(tcNewCell);
                        }*/

                        tGroups.Rows.Add(trNewRow);

                    }
                }
            }
        }

        void cmdGEdit_Click(object sender, EventArgs e)
        {
            string Group2Edit;

            //atjaunojam lietotāju sarakstu
            //dsUsers.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvUsers.DataSource = GFunc.GetData("SELECT User, LongName FROM users WHERE RecStatus=0 ORDER BY User", "WebCNS", false);
            gvUsers.DataBind();

            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            Group2Edit = b.ID.Substring(9);
            foreach (TableRow row in tGroups.Rows)
            {
                if (row.Cells[1].Text == Group2Edit)
                {
                    txtGroupID.Text = row.Cells[1].Text;
                    txtGroupName.Text = row.Cells[2].Text;
                    txtDescription.Text = row.Cells[4].Text;
                    txtUsers.Text = row.Cells[3].Text;
                    cmdCloseG.PostBackUrl = "#" + b.CommandArgument;
                    pEditGroup.Visible = true;
                    pEditUser.Visible = false;
                    txtGroupName.Focus();
                }
            }

        }

        protected void cmdNewU_Click(object sender, EventArgs e)
        {

            //atjaunojam grupu sarakstu
            //dsGroups.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvGroups.DataSource = GFunc.GetData("SELECT GroupName, Description FROM groups WHERE RecStatus=0 ORDER BY GroupName", "WebCNS", false);
            gvGroups.DataBind();

            txtNewUser.Text = "1";
            txtUser.Enabled = true;
            txtUser.Text = "";
            txtLongName.Text = "";
            txtPassword.Text = "";
            txtPassword1.Text = "";
            txtDescr.Text = "";
            txtEmail.Text = "";
            txtOldEmail.Text = "";
            txtGroups.Text = "";
            pEditUser.Visible = true;
            txtUser.Focus();

        }

        protected void cmdNewG_Click(object sender, EventArgs e)
        {
            //atjaunojam grupu sarakstu
            //dsUsers.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvUsers.DataSource = GFunc.GetData("SELECT User, LongName FROM users WHERE RecStatus=0 ORDER BY User", "WebCNS", false);
            gvUsers.DataBind();

            txtGroupID.Text = "";
            txtGroupName.Text = "";
            txtDescription.Text = "";
            txtUsers.Text = "";
            pEditGroup.Visible = true;
            txtGroupName.Focus();

        }

        protected void cmdShowG_Click(object sender, EventArgs e)
        {
            gvGroups.Visible = !gvGroups.Visible;
        }

        protected void gvGroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtGroups.Text.Contains(";" + gvGroups.SelectedRow.Cells[1].Text + ";"))
            {
                txtGroups.Text = txtGroups.Text.Replace(";" + gvGroups.SelectedRow.Cells[1].Text + ";", ";");
            }
            else
            {
                txtGroups.Text = txtGroups.Text + ";" + gvGroups.SelectedRow.Cells[1].Text + ";";
                txtGroups.Text = txtGroups.Text.Replace(";;", ";");
            }
        }

        protected void cmdShowU_Click(object sender, EventArgs e)
        {
            gvUsers.Visible = !gvUsers.Visible;
        }

        protected void gvUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtUsers.Text.Contains(";" + gvUsers.SelectedRow.Cells[1].Text + ";"))
            {
                txtUsers.Text = txtUsers.Text.Replace(";" + gvUsers.SelectedRow.Cells[1].Text + ";", ";");
            }
            else
            {
                txtUsers.Text = txtUsers.Text + ";" + gvUsers.SelectedRow.Cells[1].Text + ";";
                txtUsers.Text = txtUsers.Text.Replace(";;", ";");
            }
        }

        protected void cmdCloseU_Click(object sender, EventArgs e)
        {
            lblErrU.Text = "";
            pEditUser.Visible = false;
        }

        protected void cmdCloseG_Click(object sender, EventArgs e)
        {
            lblErrG.Text = "";
            pEditGroup.Visible = false;
        }

        protected void cmdDelU_Click(object sender, EventArgs e)
        {
            string StrDel;

            StrDel = "UPDATE users SET RecStatus=1 WHERE User='" + txtUser.Text + "'";
            GFunc.GetData(StrDel, "WebCNS", false);
            lblErrU.Text = "Lietotāja dati izdzēsti.";
        }

        protected void cmdDelG_Click(object sender, EventArgs e)
        {
            string StrDel;

            StrDel = "UPDATE groups SET RecStatus=1 WHERE GroupName='" + txtGroupName.Text + "'";
            GFunc.GetData(StrDel, "WebCNS", false);
            lblErrG.Text = "Grupa izdzēsta.";
        }

        protected bool CheckIfEmailExists(string Email)
        {
            bool EmailExists = false;
            string StrCheck = "SELECT COUNT(Email) FROM users WHERE Email = '" + Email + "'";
            DataSet dsCheck = GFunc.GetData(StrCheck, "WebCNS", false);
            if (dsCheck.Tables.Count > 0)
            {
                if (dsCheck.Tables[0].Rows.Count > 0)
                {
                    EmailExists = Convert.ToBoolean(dsCheck.Tables[0].Rows[0][0]);
                }
            }
            return EmailExists;
        }


        protected void cmdSaveU_Click(object sender, EventArgs e)
        {
            string[] c = new string[8];
            string QString = "";
            byte[] EncPass;
            string SEncPass = "";

            lblErrU.Text = "";
            if (txtPassword.Text != txtPassword1.Text)
            {
                lblErrU.Text = "Paroles neatbilst!";
                return;
            }
            if (txtUser.Text.Length == 0)
            {
                lblErrU.Text = "Nav norādīts lietotājvārds!";
                return;
            }
            try
            {
                c[0] = "User='" + GFunc.EscapeSQLCahrs(txtUser.Text) + "'";
                c[1] = "LongName='" + GFunc.EscapeSQLCahrs(txtLongName.Text) + "'";
                c[2] = "Descr='" + GFunc.EscapeSQLCahrs(txtDescr.Text) + "'";
                c[3] = "Email='" + GFunc.EscapeSQLCahrs(txtEmail.Text) + "'";
                c[4] = "Groups='" + GFunc.EscapeSQLCahrs(txtGroups.Text) + "'";
                c[5] = "UserEdit='" + GFunc.EscapeSQLCahrs(Session["UserName"].ToString()) + "'";
                c[6] = "UserAdd='" + GFunc.EscapeSQLCahrs(Session["UserName"].ToString()) + "'";
                c[7] = "TimeAdd='" + GFunc.EscapeSQLCahrs(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + "'";
                if (txtNewUser.Text == "0")
                {
                    if (!txtOldEmail.Text.Equals(txtEmail.Text))
                    {
                        if (CheckIfEmailExists(txtEmail.Text))
                        {
                            lblErrU.Text = "Norādītā e-pasta adrese jau ir reģistrēta citam lietotājam.";
                            return;
                        }
                    }
                    QString = "UPDATE users SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + " WHERE " + c[0];
                }
                else
                {
                    if (CheckIfEmailExists(txtEmail.Text))
                    {
                        lblErrU.Text = "Norādītā e-pasta adrese jau ir reģistrēta citam lietotājam.";
                        return;
                    }
                    QString = "INSERT INTO users SET " + c[0] + "," + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7];
                    txtNewUser.Text = "0";
                    txtUser.Enabled = false;
                }
                GFunc.GetData(QString, "WebCNS", false);
                //ja paroles laukā ir ievadīti dati, saglabājam datubāzē jauno paroli
                if (txtPassword.Text.Length > 0)
                {
                    SHA1 SHAProv = new SHA1CryptoServiceProvider();
                    byte[] Pass2Byte = System.Text.Encoding.ASCII.GetBytes(txtPassword.Text);
                    //Pass2Byte = txtPassword.Text.ToCharArray();
                    EncPass = SHAProv.ComputeHash(Pass2Byte);
                    SEncPass = BitConverter.ToString(EncPass).Replace("-", "").ToLower();
                    QString = "UPDATE users SET Password='" + SEncPass + "' WHERE RecStatus=0 AND User='" + txtUser.Text + "'";
                    GFunc.GetData(QString, "WebCNS", false);
                }
                SendUserData(Convert.ToBoolean(Convert.ToInt32(txtNewUser.Text)));
                lblErrU.Text = "Lietotāja dati saglabāti";
            }
            catch (Exception ex)
            {
                lblErrU.Text = ex.Message;
            }

        }
        
        protected void SendUserData(bool IsNewRec)
        {
            string MsgTo = "";
            
            if (string.IsNullOrEmpty(txtEmail.Text))
            {
                lblErrU.Text = "Dati tika saglabāti bez paziņojuma nosūtīšanas, jo lietotājam nav norādīts e-pasts.";
                return;
            }
            else
            {
                MsgTo = txtEmail.Text;
            }
            string SenderMail = "";
            DataSet dsOMailFrom = GFunc.GetData("SELECT OptValue FROM options WHERE OptType='GLOBAL' AND OptGroup='Mail' AND OptName='System e-mail'", "WebCNS", false);
            if (dsOMailFrom.Tables.Count > 0)
            {
                if (dsOMailFrom.Tables[0].Rows.Count > 0)
                {
                    SenderMail = dsOMailFrom.Tables[0].Rows[0]["OptValue"].ToString().Trim();
                }
            }
            if (SenderMail == string.Empty)
            {
                SenderMail = Session["UserEmail"].ToString();
            }

            MailMessage MMsg = new MailMessage();
            MailAddress FromAdr = new MailAddress(SenderMail);
            MMsg.From = FromAdr;
            string[] MsgRcp = MsgTo.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < MsgRcp.GetLength(0); i++)
            {
                MMsg.To.Add(MsgRcp[i]);
            }
            //aizpildam CC lauku, ja DB ir norādīti e-pasti
            string[] CCMail;
            string CCOption = "";
            dsOMailFrom = GFunc.GetData("SELECT OptValue FROM options WHERE OptType='GLOBAL' AND OptGroup='Mail' AND OptName='CC Users'", "WebCNS", false);
            if (dsOMailFrom.Tables.Count > 0)
            {
                if (dsOMailFrom.Tables[0].Rows.Count > 0)
                {
                    CCOption = dsOMailFrom.Tables[0].Rows[0]["OptValue"].ToString().Trim();
                }
            }
            if (CCOption.Length > 0)
            {
                CCMail = CCOption.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < CCMail.Length; i++)
                {
                    MailAddress CCAdr = new MailAddress(CCMail[i]);
                    MMsg.CC.Add(CCAdr);
                }
            }
            MMsg.Subject = GlobalF.AppOptions["UserDataMailSubject"];
            // HTML Body (remove HTML tags for plain text).
            string NewDocMsg = "EUROAUDIT sistēmā tika reģistrēts jauns lietotājs:";
            if (IsNewRec == false)
            {
                NewDocMsg = "EUROAUDIT sistēmā tika laboti lietotāja dati:";
            }
            string MsgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">" +
                    "<HTML>" +
                    "<HEAD>" +
                    "	<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=windows-1257\">" +
                    "</HEAD>" +
                    "<BODY LANG=\"lv-LV\" DIR=\"LTR\">" +
                    "<P><B>" + NewDocMsg + "</B></P>" +
                    "<P><BR>" +
                    "</P>" +
                    "<P>Lietotājvārds: <B>" + txtUser.Text + "</B></P>" +
                    "<P>Lietotāja vārds, uzvārds: <B>" + txtLongName.Text + "</B> " +
                    "</P>" +
                    "<P>Parole: <B>" + txtPassword.Text + "</B> " +
                    "</P>" +
                    "<P>Papildinformācija: <B>" + txtDescr.Text + "</B> " +
                    "</P>" +
                    "<P>Lietotājs ir iekļauts grupās: <B>" + txtGroups.Text + "</B> " +
                    "</P>" +
                    "</P>" +
                    "</BODY>" +
                    "</HTML>";

            MMsg.Body = MsgBody;
            MMsg.IsBodyHtml = true;

            /*// ADD AN ATTACHMENT.
            String sFile = @"C:\temp\Hello.txt";
            MailAttachment oAttch = new MailAttachment(sFile, MailEncoding.Base64);

            oMsg.Attachments.Add(oAttch);
            */
            SmtpClient SMTPmail = new SmtpClient();
            SMTPmail.Host = GlobalF.AppOptions["SMTPServer"];
            SMTPmail.Send(MMsg);


            MMsg.Dispose();

            //oAttch = null;

        }

        protected void cmdSaveG_Click(object sender, EventArgs e)
        {
            string[] c = new string[6];
            string QString = "";
            string LastID = "";
            DataSet dsLastID;
            string[] UsersInGroup;

            lblErrG.Text = "";

            if (txtGroupName.Text.Length == 0)
            {
                lblErrG.Text = "Nav norādīts grupas nosaukums!";
                return;
            }
            try
            {
                c[0] = "GroupID='" + GFunc.EscapeSQLCahrs(txtGroupID.Text) + "'";
                c[1] = "GroupName='" + GFunc.EscapeSQLCahrs(txtGroupName.Text) + "'";
                c[2] = "Description='" + GFunc.EscapeSQLCahrs(txtDescription.Text) + "'";
                c[3] = "UserEdit='" + GFunc.EscapeSQLCahrs(Session["UserName"].ToString()) + "'";
                c[4] = "UserAdd='" + GFunc.EscapeSQLCahrs(Session["UserName"].ToString()) + "'";
                c[5] = "TimeAdd='" + GFunc.EscapeSQLCahrs(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + "'";
                if (txtGroupID.Text.Length != 0)
                {
                    QString = "UPDATE groups SET " + c[1] + "," + c[2] + "," + c[3] + " WHERE " + c[0];
                }
                else
                {
                    QString = "INSERT INTO groups SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5];
                }
                dsLastID = GFunc.GetData(QString, "WebCNS", true);
                if (txtGroupID.Text.Length == 0)
                {

                    if (dsLastID.Tables.Count > 0)
                    {
                        if (dsLastID.Tables["tLID"].Rows.Count > 0)
                        {
                            txtGroupID.Text = dsLastID.Tables["tLID"].Rows[0]["LID"].ToString();
                        }
                    }
                }
                //novācam dotās grupas piesaisti visiem lietotājiem
                QString = "UPDATE users SET Groups=REPLACE(Groups,';" + txtGroupName.Text + ";',';') WHERE Groups LIKE '%;" + txtGroupName.Text + ";%'";
                GFunc.GetData(QString, "WebCNS", false);
                //pievienojam grupu norādītajiem lietotājiem
                char[] DCh = { ';' };
                UsersInGroup = txtUsers.Text.Split(DCh, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < UsersInGroup.GetLength(0); i++)
                {
                    QString = "UPDATE users SET Groups=if(instr(Groups,';" + txtGroupName.Text + ";')<1,concat(Groups,if(length(Groups)=0,';',''),'" + txtGroupName.Text + ";'),Groups) WHERE RecStatus=0 AND User='" + UsersInGroup[i] + "'";
                    GFunc.GetData(QString, "WebCNS", false);
                }
                lblErrG.Text = "Grupa saglabāta";
            }
            catch (Exception ex)
            {
                lblErrG.Text = ex.Message;
            }
        }

        protected void cmdDelOKUser_Click(object sender, EventArgs e)
        {
            //
        }

        protected void cmdDelOKGroup_Click(object sender, EventArgs e)
        {
            //
        }


    }
}
